package codepulse.blogmoon.cn.system.service.impl;

import codepulse.blogmoon.cn.common.entity.PageResult;
import codepulse.blogmoon.cn.common.enums.StatusEnum;
import codepulse.blogmoon.cn.common.exception.BizException;
import codepulse.blogmoon.cn.common.utils.BaseConvert;
import codepulse.blogmoon.cn.common.utils.PageUtil;
import codepulse.blogmoon.cn.system.dto.admin.AdminAcctInfoDTO;
import codepulse.blogmoon.cn.system.dto.admin.QueryAdminUserReq;
import codepulse.blogmoon.cn.system.entity.SysAdminAcctRoleRel;
import codepulse.blogmoon.cn.system.entity.SysAdminRole;
import codepulse.blogmoon.cn.system.entity.SysBizAccount;
import codepulse.blogmoon.cn.system.service.SysAdminAcctRoleRelService;
import codepulse.blogmoon.cn.system.service.SysAdminRoleService;
import codepulse.blogmoon.cn.system.service.SysBizAccountService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import codepulse.blogmoon.cn.system.entity.SysAdminAcctInfo;
import codepulse.blogmoon.cn.system.service.SysAdminAcctInfoService;
import codepulse.blogmoon.cn.system.mapper.SysAdminAcctInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 61748
 * @description 针对表【sys_admin_acct_info】的数据库操作Service实现
 * @createDate 2024-01-12 14:05:56
 */
@Service
public class SysAdminAcctInfoServiceImpl extends ServiceImpl<SysAdminAcctInfoMapper, SysAdminAcctInfo>
        implements SysAdminAcctInfoService {

    @Resource
    private SysBizAccountService sysBizAccountService;


    @Resource
    private SysAdminAcctRoleRelService sysAdminAcctRoleRelService;

    @Resource
    private SysAdminRoleService sysAdminRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(AdminAcctInfoDTO dto) {
        SysBizAccount sysBizAccount = sysBizAccountService.getOne(Wrappers.<SysBizAccount>lambdaQuery()
                .eq(SysBizAccount::getMobile, dto.getMobile()));
        if (Objects.isNull(sysBizAccount)) {
            if (StringUtils.isBlank(dto.getPassword())) {
                dto.setPassword(dto.getMobile().substring(dto.getMobile().length() - 6));
            }
            sysBizAccount = new SysBizAccount();
            sysBizAccount.setCreateField();
            sysBizAccount.setEmail(dto.getEmail());
            sysBizAccount.setPassword(new BCryptPasswordEncoder().encode(dto.getPassword()));
            sysBizAccount.setMobile(dto.getMobile());
            sysBizAccountService.save(sysBizAccount);
        }
        SysAdminAcctInfo baseAdminInfo = getOne(Wrappers.<SysAdminAcctInfo>lambdaQuery().eq(SysAdminAcctInfo::getBizAcctId, sysBizAccount.getId()));
        if (Objects.nonNull(baseAdminInfo)){
            throw new BizException("当前手机号已存在对应用户");
        }
        SysAdminAcctInfo sysAdminAcctInfo = BaseConvert.convert(dto, SysAdminAcctInfo.class);
        sysAdminAcctInfo.setBizAcctId(sysBizAccount.getId());
        save(sysAdminAcctInfo);

        if (CollectionUtils.isNotEmpty(dto.getRoleIds())) {
            List<SysAdminAcctRoleRel> sysAdminAcctRoleRels = dto.getRoleIds().stream().map(item -> {
                SysAdminAcctRoleRel sysAdminAcctRoleRel = new SysAdminAcctRoleRel();
                sysAdminAcctRoleRel.setAcctId(sysAdminAcctInfo.getBizAcctId());
                sysAdminAcctRoleRel.setRoleId(item);
                return sysAdminAcctRoleRel;
            }).collect(Collectors.toList());
            sysAdminAcctRoleRelService.saveBatch(sysAdminAcctRoleRels);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(AdminAcctInfoDTO dto) {
        SysBizAccount sysBizAccount = sysBizAccountService.getById(dto.getBizAcctId());
        if (Objects.isNull(sysBizAccount)) {
            throw new BizException("账号不存在");
        }
        SysAdminAcctInfo sysAdminAcctInfo = BaseConvert.convert(dto, SysAdminAcctInfo.class);
        updateById(sysAdminAcctInfo);
        SysBizAccount baseBizAccount = sysBizAccountService.getOne(Wrappers.<SysBizAccount>lambdaQuery()
                .eq(SysBizAccount::getMobile, dto.getMobile()));

        if (Objects.nonNull(baseBizAccount) && !Objects.equals(baseBizAccount.getId(), dto.getBizAcctId())) {
            throw new BizException("当前手机号已存在对应的账号信息，请重新输入手机号");
        }
        if (StringUtils.isNotBlank(dto.getPassword()) && new BCryptPasswordEncoder().matches(dto.getPassword(), sysBizAccount.getPassword())) {
            sysBizAccount.setPassword(new BCryptPasswordEncoder().encode(dto.getPassword()));
            sysBizAccountService.updateById(sysBizAccount);
        }

        if (CollectionUtils.isNotEmpty(dto.getRoleIds())) {
            sysAdminAcctRoleRelService.remove(Wrappers.<SysAdminAcctRoleRel>lambdaQuery().eq(SysAdminAcctRoleRel::getAcctId,
                    sysBizAccount.getId()));
            List<SysAdminAcctRoleRel> sysAdminAcctRoleRels = dto.getRoleIds().stream().map(item -> {
                SysAdminAcctRoleRel sysAdminAcctRoleRel = new SysAdminAcctRoleRel();
                sysAdminAcctRoleRel.setAcctId(sysAdminAcctInfo.getBizAcctId());
                sysAdminAcctRoleRel.setRoleId(item);
                return sysAdminAcctRoleRel;
            }).collect(Collectors.toList());
            sysAdminAcctRoleRelService.saveBatch(sysAdminAcctRoleRels);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAcct(Long id) {
        sysAdminAcctRoleRelService.remove(Wrappers.<SysAdminAcctRoleRel>lambdaQuery().eq(SysAdminAcctRoleRel::getAcctId,
                id));
        remove(Wrappers.<SysAdminAcctInfo>lambdaQuery().eq(SysAdminAcctInfo::getBizAcctId, id));
    }

    @Override
    public PageResult<AdminAcctInfoDTO> pageAcctInfo(QueryAdminUserReq req) {
        Page<AdminAcctInfoDTO> page = baseMapper.selectPageAcctInfo(new Page<>(req.getPageNo(), req.getPageSize()), req);
        return PageUtil.getPage(page, AdminAcctInfoDTO.class);
    }

    @Override
    public AdminAcctInfoDTO detail(Long id) {
        AdminAcctInfoDTO adminAcctInfoDTO = baseMapper.selectAcctInfoById(id);

        List<SysAdminRole> roleList = sysAdminRoleService.getRoleByAcctId(adminAcctInfoDTO.getBizAcctId());
        if (CollectionUtils.isNotEmpty(roleList)) {
            adminAcctInfoDTO.setRoleIds(roleList.stream().map(SysAdminRole::getId).collect(Collectors.toList()));
        }
        return adminAcctInfoDTO;
    }
}




